package redis

import (
	"news/models"
	"strconv"
	"time"

	"github.com/go-redis/redis"
)

func getIDsFormRangeKey(key string, page, size int64) ([]string, error) {
	//确定查询索引 的起始点
	start := (page - 1) * size
	end := start + size - 1
	//ZRevRange 查询 按分数从大到小进行排列
	return client.ZRevRange(key, start, end).Result()
}

func GetPostIdsInOrder(p *models.ParamPostIndexListForm) ([]string, error) {
	key := getRedisKey(KeyPostTimeZSet)
	if p.Order == models.OrderScore {
		key = getRedisKey(KeyPostScoreZSet)
	}
	return getIDsFormRangeKey(key, p.Page, p.Size)
}

// 根据查询的ids 查询每篇帖子投赞成票的数据
func GetPostVoteData(ids []string) (data []int64, err error) {
	pipeline := client.Pipeline()
	for _, id := range ids {
		key := getRedisKey(KeyPostVotedZSetPrefix + id)
		pipeline.ZCount(key, "1", "1")
	}
	cmder, err := pipeline.Exec()
	if err != nil {
		return nil, err
	}
	data = make([]int64, 0, len(cmder))
	for _, cmder := range cmder {
		v := cmder.(*redis.IntCmd).Val()
		data = append(data, v)
	}
	return
}

// GetCommunityPostIDsInOrder 按社区 查询ids
func GetCommunityPostIDsInOrder(p *models.ParamPostIndexListForm) ([]string, error) {
	orderkey := getRedisKey(KeyPostTimeZSet)
	if p.Order == models.OrderScore {
		orderkey = getRedisKey(KeyPostScoreZSet)
	}
	cKey := getRedisKey(KeyCommunityPostSetPrefix) + strconv.Itoa(int(p.CommunityID))

	key := orderkey + strconv.Itoa(int(p.CommunityID))
	if client.Exists(key).Val() < 1 {
		pipeline := client.Pipeline()
		pipeline.ZInterStore(key, redis.ZStore{
			Aggregate: "MAX", // 将两个zset函数聚合的时候 求最大值
		}, cKey, orderkey) // zinterstore 计算
		pipeline.Expire(key, 60*time.Second) // 设置超时时间
		_, err := pipeline.Exec()
		if err != nil {
			return nil, err
		}
	}
	// 存在的就直接根据key查询ids
	return getIDsFormRangeKey(key, p.Page, p.Size)

}
